<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div id="app"></div>

  <script>
    const obj = {}


    function defineReactive(obj, key, val) {
      // 对传入obj进行访问拦截
      Object.defineProperty(obj, key, {
        get() {
          console.log('get ' + key);
          return val
        },
        set(newVal) {
          if (newVal !== val) {
            console.log('set ' + key + ':' + newVal);
            val = newVal
            // 更新函数
            update()
          }
        }
      })
    }

    function update() {
      app.innerText = obj.foo
    }

    defineReactive(obj, 'foo', '')
    obj.foo = new Date().toLocaleTimeString()

    setInterval(() => {
      obj.foo = new Date().toLocaleTimeString()
    }, 1000);
  </script>
</body>

</html>